package com.shitou.springai1.user.controller;


import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.chat.prompt.SystemPromptTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@RestController
@RequiredArgsConstructor
public class ChatController {

    @Value("classpath:promapt/system-promapt.st")
    private Resource systemPromptResource;

    private final ChatClient chatClient;

    private final ChatModel chatModel;
    @PostMapping("/api/chat")
    public Flux<String> chat(@RequestBody Map<String, String> body, HttpServletResponse response) {
        //设置响应头，字符设置为utf-8
        response.setCharacterEncoding("utf-8");

        String question = body.getOrDefault("question", "");
        Message userMessage = new UserMessage(question);
        SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate(systemPromptResource);
        Message systemMessage = systemPromptTemplate.createMessage(Map.of(
                "name", "小凯",
                "voice", "幽默的专业风格"
        ));
        Prompt prompt = new Prompt(List.of(systemMessage,userMessage));
        //流式输出
        return chatClient.prompt(prompt).stream().content();
    }

}
